<?php

include_once "BaseController.php";

include_once dirname(__FILE__)."/../model/MemberModel.php";
include_once dirname(__FILE__)."/../model/ActivityModel.php";
include_once dirname(__FILE__)."/../util/DakaqiUtil.php";
include_once dirname(__FILE__)."/../util/WeixinUtil.php";


/**
* 用户授权处理
*/
class OauthController extends BaseController
{


	// 活动报名授权
	public function joinActivity(){

		// print_log("---in OauthController.joinActivity()");

		//获得活动编号
		$acid=isset($_GET['acid'])?$_GET['acid']:"";

		if(empty($acid)) throw new Exception("activity id is null!", 1);	

		//获得用户是否加入组织
		$joinOrg=isset($_GET["joinOrg"])?$_GET["joinOrg"]:0;	

		//获取微信用户信息
		$code=isset($_GET['code'])?$_GET['code']:"";

		if(empty($code)) throw new Exception("weixin code is null !", 1);		

		$userinfo=WeixinUtil::getUerInfo($code);

		$user=(Array)$userinfo;

		//检查用户是否已绑定
		if($this->checkBand($user['openid'])){

			//如果已经绑定过， 获取会员编号			
			$model=new MemberModel();

			$memberid=$model->getMidByOpenId($user['openid']);

			//如果用户选择加入组织，调用加入组织接口
			if($joinOrg){

				$orgid=ActivityModel::getOrgId($acid);

				DakaqiUtil::joinOrg($orgid,$memberid);
			}


			//调用报名接口 
			$data=DakaqiUtil::joinActivity($acid,$memberid);

			$json_result=$data->{"result"};

			$message=$json_result->{"desc"};			

			if($json_result->{"code"}){

				switch ($message) {
					case 0:
						$message="报名成功，等待管理员审核。";
						break;
					case 2:
						$message="报名成功";
						break;
					default:
						$message="报名异常。code:".$message;
						break;
				}

				$this->assign("message",$message);
				
				// 报名成功，进入报名成功页面
				$this->display("oauth/join_ac_success");

			}else{

				$this->assign("message",$message);

				// 报名失败，进入失败提示页面
				$this->display("oauth/join_ac_faild");
			}


		}else{

			//如果没有绑定，跳转到绑定页面，传递活动编号参数,用户信息

			$this->assign("user",$user);

			$this->assign("acid",$acid);

			$this->assign("joinOrg",$joinOrg);

			$this->display("oauth/ac_band");


		}


	}


	// 报名活动，绑定处理
	public function AcBandSubmit(){

		//获得openid
		$openid=$_POST["openid"];

		// 获取活动id
		$acid=$_POST["acid"];

		//获得是否加入组织
		$joinOrg=$_POST["joinOrg"];

		//获得手机号码
		$mobile=isset($_POST["mobile"])?$_POST["mobile"]:"";
		
		$member_model=new MemberModel();

		// 通过手机号码，检查账号是否存在
		$mid=$member_model->getMidByMobile($mobile);
		
		if(empty($mid)){

			// 如果没找到会员资料，注册用户
			$nickname=$_POST["nickname"];
			$realname=$_POST["realname"];
			$sex=$_POST["sex"]==1?"男":"女";
			$headUrl=$_POST["headimgurl"];

			$member_info = array('nickname' => $nickname, 'realname' => $realname,'sex' => $sex,
				'headUrl' => $headUrl,'headUrlm' => $headUrl,'headUrls' => $headUrl,
				'mobile' => $mobile,'weixin_openid' => $openid);
			
			$data=$member_model->regist($member_info);

			if($data["result"]["code"]==1){

				// 会员资料注册成功
				$mid=$data["memberID"];

			}else{

				// 注册失败
				$this->assign("message",$data["result"]["desc"]);

				// 报名失败，进入失败提示页面
				$this->display("oauth/join_ac_faild");

				exit();

			}

		}else{

			// 如果通过手机号码找到会员资料， 绑定用户
			$member_model->bandByMid($mid,$openid);
		}

		//检查用户是否加入组织
		if($joinOrg){

			$orgid=ActivityModel::getOrgId($acid);

			DakaqiUtil::joinOrg($orgid,$mid);
		}


		//调用报名接口 
		$data=DakaqiUtil::joinActivity($acid,$mid);

		$json_result=$data['result'];

		$message=$json_result['desc'];			

		if($json_result['code']){

			switch ($message) {
				case 0:
					$message="报名成功，等待管理员审核。";
					break;
				case 2:
					$message="报名成功";
					break;
				default:
					$message="报名异常。code:".$message;
					break;
			}

			$this->assign("message",$message);
			
			// 报名成功，进入报名成功页面
			$this->display("oauth/join_ac_success");

		}else{

			$this->assign("message",$message);

			// 报名失败，进入失败提示页面
			$this->display("oauth/join_ac_faild");
		}


	}

	
	// 授权处理，获取用户信息,进入账号绑定界面
	public function band(){

        print_log("--- in OauthController -> band()");

		//1. 获取code
		$code=isset($_GET['code'])?$_GET['code']:"";

		if(empty($code)) throw new Exception("code is null", 1);


        print_log("--- \$code:$code");

		// 2.使用code 获得 userinfo
		$userinfo=WeixinUtil::getUerInfo($code);

//        print_log($userinfo);

        print_log(is_array($userinfo));

        print_log("--open_id:".$userinfo['openid']);

		// 通过openId 检查会员是否已经绑定，如果已绑定，跳转到绑定成功页面
		if($this->checkBand($userinfo['openid'])){

			$this->display("oauth/band_success");

			exit();
		} 
		

		$this->assign("url_connect_code",getConfig("url_connect_code"));
		$this->assign("app_id",getConfig("app_id"));
		$this->assign("app_path",getConfig("APP_PATH"));


		$this->assign("user",$userinfo);

		$this->display("oauth/band");

	}



	// 与志愿者打卡器账号绑定
	public function bandSubmit(){

		//获得openid
		$openid=$_POST["openid"];


		//获得手机号码
		$mobile=isset($_POST["mobile"])?$_POST["mobile"]:"";

		//获取登陆密码
		$password=isset($_POST["password"])?$_POST["password"]:"";

		if(empty($mobile) || empty($password)){

			throw new Exception("账号或密码为空！", 500);
			
		}

		$password=md5($password);

		$member=new MemberModel();

		//检查账号是否存在
		$mid=$member->checkExists($mobile,$password);

		if(empty($mid)){

			// 如果账号不存在，跳转到失败页面
			$this->assign("message","该账号不存在");

			$this->display("oauth/band_faild");

		}else{

			//执行绑定
			$member->bandByMid($mid,$openid);

			$this->display("oauth/band_success");

		}

		
	}


	// 检查是否已经绑定打卡器账号，已绑定返回 true ，否则返回false
	private function checkBand($openid){

        print_log("--- check band for open_id:$openid");

		$member=new MemberModel();

		$isband=$member->checkBand($openid);

		return $isband;
	}


	// 进入绑定注册页面
	function registBand(){

		//1. 获取code
		$code=isset($_GET['code'])?$_GET['code']:"";

		if(empty($code)) throw new Exception("code is null", 1);
		

		// 2.使用code 获得 userinfo
		$userinfo=WeixinUtil::getUerInfo($code);

		$this->assign("user",$userinfo);

		$this->display("oauth/band_regist");
	}


	// 注册打卡器账号，同时绑定账号
	function registBandSubmit(){

		try {

			$openid=$_POST["openid"];
			$mobile=isset($_POST["mobile"])?$_POST["mobile"]:"";
			$nickname=$_POST["nickname"];
			$realname=$_POST["realname"];
			$sex=$_POST["sex"]==1?"男":"女";
			$headUrl=$_POST["headimgurl"];

			$member_info = array('nickname' => $nickname, 'realname' => $realname,'sex' => $sex,
				'headUrl' => $headUrl,'headUrlm' => $headUrl,'headUrls' => $headUrl,
				'mobile' => $mobile,'weixin_openid' => $openid);
			
			$member_model=new MemberModel();

			$data=$member_model->regist($member_info);

			if($data["result"]["code"]==0){

				// 会员资料注册失败
				throw new Exception($data["result"]["desc"], 1);		

			}

			$this->display("oauth/band_success");
			
		} catch (Exception $e) {
			
			$this->assign("message",$e->getMessage());

			$this->display("oauth/band_faild");
		}

	}

}


 ?>